package com.tungse.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

/**
 * @author Tungse
 */
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                     .channel(NioServerSocketChannel.class)
                     .childHandler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel ch) {
                             // 1. 解决粘包拆包：消息头（4字节长度）+ 消息体
                             ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(
                                     1024,       // max frame length
                                     0,         // length field offset (header starts at 0)
                                     4,         // length field size (int = 4 bytes)
                                     0,         // length adjustment
                                     4          // bytes to strip (after decoding)
                             ));
                             // +++ 新增编码器（处理出站数据） +++
                             ch.pipeline().addLast(new LengthFieldPrepender(4));
                             // 2. 自定义业务处理器
                             ch.pipeline().addLast(new ServerHandler());
                         }
                     });

            ChannelFuture future = bootstrap.bind(8080).sync();
            System.out.println("Netty 服务端启动，监听 8080 端口...");
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}